from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin

from common.func import check_token
from user.models import User


class MyMiddleware(MiddlewareMixin):

    # 在视图函数之前
    def process_request(self, request):

        # 排除 发短信和 登录的路由
        white_url = ['/api/sms/', '/api/login/']
        if request.path in white_url:
            return

        # 获取头部的token验证
        token = request.META.get('HTTP_TOKEN')

        # 验证token
        res, phone = check_token(token)

        if not res:
            return JsonResponse({'code':1003, 'data': '非法用户'})
        else:
            # token的值正确,还要验证 载荷中的 手机号 是否存在于 表中
            try:
                user = User.objects.get(phonenum=phone)
            except User.DoesNotExist:
                return JsonResponse({'code': 1004, 'data': '用户不存在'})

            request.user = user
